<template>
    <div class="container-fluid" v-loading="loading">

        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        {{ companyName }}
                        &nbsp;&nbsp; <el-button size="mini" type="danger" v-if="status===1" @click="handleSetStatus(companyId,0)">停用</el-button>
                        <el-button size="mini" type="success" v-if="!status" @click="handleSetStatus(companyId,1)">开启</el-button>
                    </div>
                    <div class="card-toolbar clearfix">
                        <form class="form-inline" onsubmit="return false;">
                            <div class="form-group">
                                <label>公司别名</label>
                                <el-tag
                                        :key="tag"
                                        v-for="tag in alternativeName"
                                        closable
                                        :disable-transitions="false"
                                        @close="handleClose(tag)">
                                    {{tag}}
                                </el-tag>
                                <el-input
                                        class="input-new-tag"
                                        v-if="inputVisible"
                                        v-model="inputValue"
                                        ref="saveTagInput"
                                        @keyup.enter.native="handleInputConfirm"
                                        @blur="handleInputConfirm"
                                        style="width: 40%;"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加公司别称
                                </el-button>
                            </div>

                            <!--<div class="form-group">
                                <label>所属分类</label>
                                <el-autocomplete
                                        v-model="categoryName"
                                        :fetch-suggestions="querySearchAsync"
                                        placeholder="请输入内容"
                                        @select="handleSelect"
                                ></el-autocomplete>
                                <el-tag
                                        :key="tag.id"
                                        v-for="tag in categoryTags"
                                        closable
                                        :disable-transitions="false"
                                        @close="handleIndustryClose(tag)">
                                    {{tag.value}}
                                </el-tag>
                            </div>-->

                        </form>
                    </div>

                    <company-menu-components :company-id="companyId" :active-index="activeIndex"></company-menu-components>

                    <div class="card-toolbar clearfix">
                        <form class="pull-right search-bar" onsubmit="return false;">
                            <div class="input-group-btn">
                                <input type="text" class="form-control" v-model="keyword" placeholder="请输入名称">

                            </div>

                            <div class="input-group-btn">
                                <button class="btn btn-success" type="submit" v-on:click="search()">筛选</button>
                            </div>
                        </form>
                        <div class="toolbar-btn-action">
                            <a class="btn btn-primary m-r-5" :href="'/admin/goods/create/'+companyId"><i class="mdi mdi-plus"></i> 新增</a>
                        </div>
                    </div>

                    <div class="card-body">
                        <div class="table-responsive" style="width: 100%;margin-top: 20px;">
                            <el-table
                                    :data="list"
                                    style="width: 100%"
                                    :default-sort="{prop: 'date', order: 'descending'}"
                            >
                                <el-table-column
                                        label="ID"
                                        type="index"
                                        :index="indexMethod"
                                        width="50">
                                </el-table-column>
                                <el-table-column
                                        prop="name"
                                        label="产品名称"
                                        width="80">
                                    <template slot-scope="scope">
                                        <a @click="openEdit(scope.row._id)" style="cursor:pointer;">{{scope.row.name |
                                            titleFormatter}}</a>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                        prop="companyName"
                                        label="所属公司"
                                        width="80">
                                </el-table-column>
                                <el-table-column
                                        prop="price"
                                        label="价格数字"
                                        width="80">
                                </el-table-column>
                                <el-table-column
                                        label="置顶状态"
                                        align="center"
                                        width="80">
                                    <template slot-scope="scope">
                                        <p v-if="scope.row.isTop">是</p>
                                        <p v-else>否</p>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                        label="操作"
                                        align="center"
                                        width="180">
                                    <template slot-scope="scope">
                                        <el-button v-if="scope.row.isTop" size="mini" @click="setTop(scope.row._id,0)" type="primary">取消置顶</el-button>
                                        <el-button v-else size="mini" @click="setTop(scope.row._id,1)" type="success">置顶</el-button>
                                        <el-button
                                                size="mini"
                                                type="danger"
                                                @click="handleDelete(scope.row)">删除
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>

                            <nav style="float: right;">
                                <el-pagination
                                        layout="prev, pager, next"
                                        :total="total" :hide-on-single-page="pageActive"
                                        :page-size="pageSize"
                                        :current-page="currentPage"
                                        @current-change="handleCurrentChange"
                                >
                                </el-pagination>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</template>

<script>
    import CompanyMenuComponents from "./CompanyMenuComponents";
    export default {
        name: "CompanyGoodsComponent",
        components: {
            "company-menu-components": CompanyMenuComponents,
        },
        data() {
            return {
                keyword: '',
                pageActive: false,
                list: [],
                pageSize: 10,
                total: 0,
                currentPage: 1,
                loading: true,
                activeIndex: '3',
                name: '',
                order: 'desc',
                orderField: '_id',
                form: {
                    name: "",
                    //categoryName: '',
                    editName: "",
                    editIndustryName: '',
                    editAlternativeName: [],
                },

                formLabelWidth: '120px',
                dialogTableVisible: false,
                //公司部分
                alternativeName: [],
               /* categoryName: '',
                categoryTags: [],
                categoryIds: [],*/
                inputVisible: false,
                inputValue: '',
                companyName:'',
                status:0,
                companyId: $('meta[name="id"]').attr('content'),
            }
        },
        methods: {
            search: function () {
                let self = this;
                let url = 'company/post-goods';
                self.loading = true;
                let postData = {
                    keyword: self.keyword,
                    page: self.currentPage,
                    order: self.order,
                    orderField: self.orderField,
                    verifyStatus: 1,
                    companyId: self.companyId,
                    userId:0
                };
                axios.post(url, postData).then(function (result) {
                    self.total = result.goods.total;
                    if (self.total > 0) {
                        self.pageActive = false;
                    } else {
                        self.pageActive = true;
                    }
                    self.list = result.goods.data;
                    self.loading = false;
                }).catch(function (error) {
                    self.loading = false;
                })
            },
            setTop(id,top) {
                let self = this;
                let uri = "goods/set-top/"+id+"/"+top;
                axios.get(uri).then(function (result) {
                    self.search();
                });
            },
            handleDelete: function (row) {
                let self = this;
                let tipStr = "此操作将永久删除“" + row.name + "”, 是否继续?";
                self.$confirm(tipStr, '产品删除', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    self.deleteRequire(row._id)
                }).catch(() => {
                    self.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            deleteRequire: function (id) {
                let self = this;
                let uri = "goods/" + id;
                self.loading = true;

                axios.delete(uri).then(function (result) {
                    self.search();
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            getInfo() {
                let self = this;
                let uri = "company/" + self.companyId;
                self.loading = true;

                axios.get(uri).then(function (data) {
                    let result = data.result;
                    self.companyName = result.name;
                    self.status = 0;
                    self.status = result.status;
                    /*self.categoryIds = [];
                    self.categoryTags = [];*/
                    self.alternativeName = [];
                    self.alternativeName = result.alternativeName;
                    /*self.categoryTags = result.categoryNames;
                    result.categoryNames.forEach((item) => {
                        self.categoryIds.push(item.id)
                    });*/
                    self.loading = false;
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            handleCurrentChange: function (val) {
                this.currentPage = val;
                this.search();
            },
            indexMethod: function (index) {
                return index + 1;
            },

            //下面是标签部分
            handleClose(tag) {
                console.log(tag);
                this.alternativeName.splice(this.alternativeName.indexOf(tag), 1);
                this.updateCompany();
            },
            showInput() {
                this.inputVisible = true;
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            handleInputConfirm() {
                let inputValue = this.inputValue;

                if (inputValue && this.alternativeName.indexOf(inputValue) == -1) {
                    this.alternativeName.push(inputValue);
                    this.updateCompany();
                }
                this.inputVisible = false;
                this.inputValue = '';
            },
            //查询分类
            queryIndustry(keyword = '') {
                let self = this;
                let uri = "category/search/"+keyword;
                axios.get(uri).then(function (result) {
                    self.restaurants = result.list;
                });
            },
            querySearchAsync(queryString, cb) {
                var restaurants = this.restaurants;
                var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 1000 * Math.random());
            },
            handleSelect(item) {

                if (item && this.categoryIds.indexOf(item.id) == -1) {
                    this.categoryTags.push(item);
                    this.categoryIds.push(item.id);
                    this.updateCompany();
                }
                this.categoryName = '';
            },
            handleIndustryClose(tag) {
                this.categoryTags.splice(this.categoryTags.indexOf(tag), 1);
                this.categoryIds.splice(this.categoryIds.indexOf(tag.id),1);
                this.updateCompany();
            },
            updateCompany() {
                let self = this;
                self.loading = true;
                let url = "company/update/" + self.companyId;
                let postData = {
                    alternativeName: self.alternativeName,
                    //categoryIds: self.categoryIds
                };
                axios.put(url, postData).then(function (result) {
                    self.getInfo();
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            handleSetStatus(id,status){
                let self = this;
                let uri = "company/set-status/"+id+"/"+status;
                axios.get(uri).then(function (result) {
                    self.getInfo();
                });
            },
            openEdit(id) {
                this.openUri('goods/' + id + '/edit');
            },
        },
        mounted() {
            this.queryIndustry();
            this.search();
            this.getInfo();
        },
        filters: {
            titleFormatter(title) {
                if (title.length >= 10) {
                    return title.substring(0, 10) + '...';
                }
                return title.length === 0 ? '--' : title;
            }
        }
    }
</script>

<style scoped>
    .form-inline .form-group {
        display: block;
        margin-bottom: 15px;
    }
    .input-group-addon, .input-group-btn
    {
        width:100%;
    }
</style>
